import { WebSocketServer, WebSocket, EventEmitter } from "ws"
import { Connection, ConnectionEventType } from "./Connection"
import { ApiMsgEnum, IModel } from "../Common"
export enum ServerEventType {
    // 有连接进入
    connection = 'connection',
    // 有连接断开
    disconnection = 'disconnection',
}

export class MyServer extends EventEmitter {

    private connections: Set<Connection> = new Set()
    private port: number

    apiMap: Map<ApiMsgEnum, Function> = new Map()

    constructor(port = 8888) {
        super()
        this.port = port
    }

    async start() {
        return new Promise((resolve, reject) => {
            const wss = new WebSocketServer({
                port: this.port
            })
            wss.on('close', () => {
                console.log('服务关闭')
                reject(false)
            })
            wss.on('error', (e: Error) => {
                console.log('服务错误：', e)
                reject(false)
            })
            wss.on('listening', () => {
                console.log('服务启动成功')
                resolve(true)
            })
            wss.on('connection', (socket: WebSocket) => {
                const connection = new Connection(this, socket)
                this.connections.add(connection)
                this.emit(ServerEventType.connection, connection)
                connection.on(ConnectionEventType.close, () => {
                    this.emit(ServerEventType.disconnection, connection)
                    this.connections.delete(connection)
                })
            })
        })
    }

    setApi<T extends keyof IModel['api']>(name: T, fun: (connection: Connection, data: IModel['api'][T]['req']) => IModel['api'][T]['res']) {
        this.apiMap.set(name, fun)
    }

}